﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Clock
{
    public partial class Form1 : Form
    {
        private NotifyIcon notifyIcon;
        private ContextMenuStrip contextMenuStrip;
        private ToolStripMenuItem exitToolStripMenuItem;
        private ToolStripMenuItem restartToolStripMenuItem;
        private ToolStripMenuItem configToolStripMenuItem;
        private bool isDragging = false;
        private Point dragStartPoint;

        private int worktileDuration = int.Parse(ConfigurationManager.AppSettings["work_duration"].ToString().Trim());
        private int breakDuration = int.Parse(ConfigurationManager.AppSettings["break_duration"].ToString().Trim());

        public Form1()
        {
            InitializeComponent();

            // 设置窗体不显示在任务栏
            this.ShowInTaskbar = false;

            // 初始化 NotifyIcon 控件
            notifyIcon = new NotifyIcon();
            notifyIcon.Icon = new Icon("Resources/clock.ico"); // 设置图标，替换为你的图标资源
            notifyIcon.Text = "Clock"; // 设置提示文本
            notifyIcon.Visible = true; // 设置可见

            // 创建ContextMenuStrip
            contextMenuStrip = new ContextMenuStrip();
            // 添加菜单项到ContextMenuStrip
            exitToolStripMenuItem = new ToolStripMenuItem("Exit");
            exitToolStripMenuItem.Click += new EventHandler(exitToolStripMenuItem_Click);
            contextMenuStrip.Items.Add(exitToolStripMenuItem);
            // 再加一个重启的菜单项（修改配置文件后让重启生效）
            /* --- 用不到了
            restartToolStripMenuItem = new ToolStripMenuItem("Restart");
            restartToolStripMenuItem.Click += new EventHandler(restartToolStripMenuItem_Click);
            contextMenuStrip.Items.Add(restartToolStripMenuItem);
            用不到了 --- */
            // 再加一个修改配置文件的菜单项
            configToolStripMenuItem = new ToolStripMenuItem("Config");
            configToolStripMenuItem.Click += new EventHandler(configToolStripMenuItem_Click);
            contextMenuStrip.Items.Add(configToolStripMenuItem);


            // 将ContextMenuStrip分配给NotifyIcon
            notifyIcon.ContextMenuStrip = contextMenuStrip;

            // 增加鼠标拖动功能
            this.MouseDown += new MouseEventHandler(Form_MouseDown);
            this.MouseMove += new MouseEventHandler(Form_MouseMove);
            this.MouseUp += new MouseEventHandler(Form_MouseUp);


            this.DoubleBuffered = true; // 减少闪烁
            this.FormBorderStyle = FormBorderStyle.None;
            this.TopMost = true;
            this.BackColor = Color.Black;
            this.TransparencyKey = Color.Black; // 设置透明背景色
            this.Size = new Size(220, 220);

            clockTimer = new Timer();
            clockTimer.Interval = TickInterval;
            clockTimer.Tick += ClockTimer_Tick;
            clockTimer.Start();
        }

        private void Form_MouseDown(object sender, MouseEventArgs e)
        {
            // 如果点击的是鼠标左键，则开始记录拖动起始位置
            if (e.Button == MouseButtons.Left)
            {
                isDragging = true;
                dragStartPoint = new Point(e.X, e.Y);
            }
        }

        private void Form_MouseMove(object sender, MouseEventArgs e)
        {
            // 如果正在拖动，则计算窗体的新位置并移动窗体
            if (isDragging)
            {
                Point currentScreenPoint = this.PointToScreen(e.Location);
                this.Location = new Point(currentScreenPoint.X - dragStartPoint.X, currentScreenPoint.Y - dragStartPoint.Y);
            }
        }

        private void Form_MouseUp(object sender, MouseEventArgs e)
        {
            // 鼠标释放时，停止拖动
            isDragging = false;
        }

        public void Form1_Load(object sender, System.EventArgs e)
        {
            // 设置窗口的起始位置为手动
            this.StartPosition = FormStartPosition.Manual;
            // 获取屏幕的工作区域（不包括任务栏）
            Rectangle screen = Screen.FromControl(this).WorkingArea;
            // 计算窗口右下角位于屏幕右下角时的窗口位置
            int x = screen.Right - this.Width;
            int y = screen.Bottom - this.Height;
            // 设置窗口的位置
            this.Location = new Point(x, y);
        }

        private Timer clockTimer;
        private const int TickInterval = 1000; // 1秒
        private const int ClockRadius = 100;
        private const int HourHandLength = 60;
        private const int MinuteHandLength = 80;
        private const int SecondHandLength = 90;

        private void ClockTimer_Tick(object sender, EventArgs e)
        {
            this.Invalidate(); // 请求重绘窗体
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            DrawClock(e.Graphics);
        }

        private void DrawClock(Graphics g)
        {
            int centerX = this.Width / 2;
            int centerY = this.Height / 2;

            // 绘制刻度
            for (int i = 0; i < 60; i++)
            {
                float angle = (float)(i * 6.0 * Math.PI / 180.0);
                int x = (int)(centerX + ClockRadius * Math.Sin(angle));
                int y = (int)(centerY - ClockRadius * Math.Cos(angle));

                if (i % 5 == 0) // 大刻度
                {
                    // g.DrawLine(Pens.DarkGray, x, y, (int)(x + 5 * Math.Sin(angle)), (int)(y - 5 * Math.Cos(angle)));

                    Font font = new Font("Arial", 12);
                    string s = i / 5 + "";
                    if (i == 0)
                    {
                        s = "12";
                    }

                    // 计算文本尺寸
                    SizeF textSize = g.MeasureString(s, font);
                    // 计算绘制的起始位置，使文本中心与指定点重合
                    float drawPositionX = x - (textSize.Width / 2);
                    float drawPositionY = y - (textSize.Height / 2);

                    g.DrawString(s, font, Brushes.White, drawPositionX, drawPositionY);
                }
                else // 小刻度
                {
                    g.DrawLine(Pens.LightGray, x, y, (int)(x + 3 * Math.Sin(angle)), (int)(y - 3 * Math.Cos(angle)));
                }
            }

            // 绘制时针、分针和秒针
            DateTime now = DateTime.Now;
            DrawHand_Hour(g, now, centerX, centerY, HourHandLength, 6); // 时针
            DrawHand_Minute(g, now, centerX, centerY, MinuteHandLength, 4); // 分针
            DrawHand_Second(g, now, centerX, centerY, SecondHandLength, 2); // 秒针
        }

        private void DrawHand_Second(Graphics g, DateTime now, int centerX, int centerY, int length, int width)
        {
            int second = now.Second;
            float angle = (float)(second / 60.0 * 360 * Math.PI / 180.0);
            int x2 = (int)(centerX + length * Math.Sin(angle));
            int y2 = (int)(centerY - length * Math.Cos(angle));

            using (Pen pen = new Pen(Color.Yellow, width))
            {
                g.DrawLine(pen, centerX, centerY, x2, y2);
            }
        }

        private void DrawHand_Minute(Graphics g, DateTime now, int centerX, int centerY, int length, int width)
        {
            int minute = now.Minute;
            int second = now.Second;
            float angle = (float)((minute + second / 60.0) / 60.0 * 360 * Math.PI / 180.0);
            int x2 = (int)(centerX + length * Math.Sin(angle));
            int y2 = (int)(centerY - length * Math.Cos(angle));

            using (Pen pen = new Pen(Color.Red, width))
            {
                g.DrawLine(pen, centerX, centerY, x2, y2);
            }

            if (minute% worktileDuration == 0 && second==0)
            {
                Form myForm = new Form
                {
                    Width = 351,
                    Height = 359,
                    Text = "休息点: 将在" + breakDuration + "分钟后自动关闭",
                    TopMost = true,
                    StartPosition = FormStartPosition.CenterScreen,
                    FormBorderStyle = FormBorderStyle.FixedDialog,
                    ControlBox = false, // 去除控制框（最小化、最大化、关闭按钮）  
                    ShowInTaskbar = false // 不在任务栏显示  
                };

                //// 添加一个Label来显示消息  
                //Label label = new Label
                //{
                //    AutoSize = true,
                //    Location = new System.Drawing.Point(100, 20),
                //    Text = "将在"+breakDuration+"分钟后自动关闭"
                //};
                //myForm.Controls.Add(label);

                // 添加一个PictureBox来显示图片  
                PictureBox pictureBox = new PictureBox
                {
                    SizeMode = PictureBoxSizeMode.AutoSize, // 或者使用其他模式，如StretchImage  
                    Location = new System.Drawing.Point(0, 0), // 假设Label下方留出30像素的空间  
                    Image = Image.FromFile("Resources/bg.png") // 替换为您的图片路径  
                };
                myForm.Controls.Add(pictureBox);

                // 显示Form  
                myForm.Show();

                // 在后台执行倒计时  
                Task.Run(() =>
                {
                    // System.Threading.Thread.Sleep(5000); // 等待5秒  
                    //System.Threading.Thread.Sleep(180000); // 等待3分钟
                    System.Threading.Thread.Sleep(breakDuration * 60 * 1000); // 等待breakDuration分钟 
                    myForm.Invoke(new Action(myForm.Close)); // 使用Invoke来确保在UI线程上关闭Form  
                });

                // 增强提醒
                MessageBox.Show("请离开鼠标键盘和屏幕，思考接下来要做什么，想不出来的话就去睡觉", "要有主动计划的事");
            }
        }

        private void DrawHand_Hour(Graphics g, DateTime now, int centerX, int centerY, int length, int width)
        {
            int hour = now.Hour;
            int minute = now.Minute;
            int second = now.Second;
            float angle = (float)((hour + minute / 60.0 + second / 60.0 / 60.0) / 12.0 * 360 * Math.PI / 180.0);
            int x2 = (int)(centerX + length * Math.Sin(angle));
            int y2 = (int)(centerY - length * Math.Cos(angle));

            using (Pen pen = new Pen(Color.Blue, width))
            {
                g.DrawLine(pen, centerX, centerY, x2, y2);
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void restartToolStripMenuItem_Click(Object sender, EventArgs e)
        {
            Application.Restart();
        }

        private void configToolStripMenuItem_Click(Object sender, EventArgs e)
        {
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = "notepad.exe";
            startInfo.Arguments = @"D:\sean\Clock\bin\Debug\Clock.exe.config";

            using (Process process = Process.Start(startInfo))
            {
                process.WaitForExit();
                Application.Restart();
            }
        }
    }
}
